﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using InspectionMAC.Function;
using csLTDMC;
using InspectionMAC.SystemThread;
using System.IO;
using LitJson;
using System.Collections.Concurrent;

namespace InspectionMAC.Forms
{
    public partial class PointSetForm : Form
    {
        // 实例字段（非静态）
        private bool RecordLocation1_Flowrec = false;
        private Thread RecordLocation1Flow_Thread = null;
        private int iRecordLocation1_Step = 0;

        private bool RecordLocation2_Flowrec = false;
        private Thread RecordLocation2Flow_Thread = null;
        private int iRecordLocation2_Step = 0;

        private bool RecordLocation3_Flowrec = false;
        private Thread RecordLocation3Flow_Thread = null;
        private int iRecordLocation3_Step = 0;

        public PictureBox[] pictureBoxes = new PictureBox[3];

        public PointSetForm()
        {
            InitializeComponent(); 
        }

        private void PointSetForm_Load(object sender, EventArgs e)
        {
            cameraPb_01.SizeMode = PictureBoxSizeMode.Zoom;

            cameraPb_02.SizeMode = PictureBoxSizeMode.Zoom;

            cameraPb_03.SizeMode = PictureBoxSizeMode.Zoom;

            OldSensorDistanceTb.Text = MaterialTracker.SENSOR1_TO_SENSOR2_DISTANCE.ToString();
            RecordLocation_Thread();


            pictureBoxes[0] = cameraPb_01;
            pictureBoxes[1] = cameraPb_02;
            pictureBoxes[2] = cameraPb_03;
            cameraPb_01.SizeMode = PictureBoxSizeMode.Zoom;
            cameraPb_02.SizeMode = PictureBoxSizeMode.Zoom;
            cameraPb_03.SizeMode = PictureBoxSizeMode.Zoom;

            InitializeDisplayTimer();

            CameraContinuesThread01.iCameraContinues_Step = 0;
            string filePath1 = MacTestForm.SettingsFilePath;
            JsonData jsonData1;
            string jsonContent1 = File.ReadAllText(filePath1);
            jsonData1 = JsonMapper.ToObject(jsonContent1);
            textBox1.Text = (jsonData1["TaskGroup3"]["Interval"]).ToString();
            textBox2.Text = (jsonData1["TaskGroup2"]["Interval"]).ToString();
            textBox3.Text = (jsonData1["TaskGroup1"]["Interval"]).ToString();
        }
        public static ConcurrentQueue<Bitmap> DisplayQueue01 = new ConcurrentQueue<Bitmap>();
        public static ConcurrentQueue<Bitmap> DisplayQueue02 = new ConcurrentQueue<Bitmap>();
        public static ConcurrentQueue<Bitmap> DisplayQueue03 = new ConcurrentQueue<Bitmap>();

        private System.Windows.Forms.Timer displayUpdateTimer;

        private void DisplayUpdateTimer_Tick(object sender, EventArgs e)
        {
            UpdateDisplay(sender, e); // 更新图像显示
        }
        private void InitializeDisplayTimer()
        {
            displayUpdateTimer = new System.Windows.Forms.Timer();
            displayUpdateTimer.Interval = 100; // 100毫秒更新一次
            displayUpdateTimer.Tick += DisplayUpdateTimer_Tick;
            displayUpdateTimer.Start();
        }

        private void UpdateDisplay(object sender, EventArgs e)
        {
            // 更新工位1
            if (DisplayQueue01.TryDequeue(out Bitmap bmp1))
            {
                lastQueueUpdateTime = DateTime.Now; // 重置时间
                UpdatePictureBox(cameraPb_01, bmp1);
            }

            // 更新工位2
            if (DisplayQueue02.TryDequeue(out Bitmap bmp2))
            {
                lastQueueUpdateTime = DateTime.Now; // 重置时间
                UpdatePictureBox(cameraPb_02, bmp2);
            }

            // 更新工位3
            if (DisplayQueue03.TryDequeue(out Bitmap bmp3))
            {
                lastQueueUpdateTime = DateTime.Now; // 重置时间
                UpdatePictureBox(cameraPb_03, bmp3);
            }
        }

        private void UpdatePictureBox(PictureBox pictureBox, Bitmap newImage)
        {
            if (pictureBox.InvokeRequired)
            {
                pictureBox.Invoke(new Action<PictureBox, Bitmap>(UpdatePictureBox), pictureBox, newImage);
                return;
            }

            // 释放旧图像
            if (pictureBox.Image != null)
            {
                var oldImage = pictureBox.Image;
                pictureBox.Image = null;
                oldImage.Dispose();
            }

            pictureBox.Image = newImage;
        }
        
        public void UpdateSensor1Location(string text)
        {
            if (Sensor1Location.InvokeRequired)
            {
                Sensor1Location.BeginInvoke((MethodInvoker)delegate
                {
                    Sensor1Location.Text = text;
                });
            }
            else
            {
                Sensor1Location.Text = text;
            }
        }

        public void UpdateSensor2Location(string text)
        {
            if (Sensor2Location.InvokeRequired)
            {
                Sensor2Location.BeginInvoke((MethodInvoker)delegate
                {
                    Sensor2Location.Text = text;
                });
            }
            else
            {
                Sensor2Location.Text = text;
            }
        }



        // 改为实例方法
        public void RecordLocation_Thread()
        {
            // 启动传感器1位置记录线程
            RecordLocation1_Flowrec = true;
            if (RecordLocation1Flow_Thread == null)
            {
                RecordLocation1Flow_Thread = new Thread(RecordLocation1FlowThread);
                RecordLocation1Flow_Thread.IsBackground = true;
                RecordLocation1Flow_Thread.Start();
                iRecordLocation1_Step = 10;
            }
            else if (!RecordLocation1Flow_Thread.IsAlive)
            {
                // 如果线程存在但未运行，重新创建线程
                RecordLocation1Flow_Thread = new Thread(RecordLocation1FlowThread);
                RecordLocation1Flow_Thread.IsBackground = true;
                RecordLocation1Flow_Thread.Start();
                iRecordLocation1_Step = 10;
            }
            // 如果线程已经在运行，不做任何操作

            // 启动传感器2位置记录线程
            RecordLocation2_Flowrec = true;
            if (RecordLocation2Flow_Thread == null)
            {
                RecordLocation2Flow_Thread = new Thread(RecordLocation2FlowThread);
                RecordLocation2Flow_Thread.IsBackground = true;
                RecordLocation2Flow_Thread.Start();
                iRecordLocation2_Step = 10;
            }
            else if (!RecordLocation2Flow_Thread.IsAlive)
            {
                // 如果线程存在但未运行，重新创建线程
                RecordLocation2Flow_Thread = new Thread(RecordLocation2FlowThread);
                RecordLocation2Flow_Thread.IsBackground = true;
                RecordLocation2Flow_Thread.Start();
                iRecordLocation2_Step = 10;
            }

            RecordLocation3_Flowrec = true;
            if (RecordLocation3Flow_Thread == null)
            {
                RecordLocation3Flow_Thread = new Thread(RecordLocation3FlowThread);
                RecordLocation3Flow_Thread.IsBackground = true;
                RecordLocation3Flow_Thread.Start();
                iRecordLocation3_Step = 10;
            }
            else if (!RecordLocation3Flow_Thread.IsAlive)
            {
                // 如果线程存在但未运行，重新创建线程
                RecordLocation3Flow_Thread = new Thread(RecordLocation2FlowThread);
                RecordLocation3Flow_Thread.IsBackground = true;
                RecordLocation3Flow_Thread.Start();
                iRecordLocation3_Step = 10;
            }
        }

        // 改为实例方法
        private void RecordLocation1FlowThread(object obj)
        {
            while (RecordLocation1_Flowrec)
            {
                switch (iRecordLocation1_Step)
                {
                    case 0:
                        // 初始状态
                        break;

                    case 10:
                        if (DIO_Thread.Di[11] == 1)
                        {
                            UInt32 nEnPos = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 2);
                            // 通过单例实例更新UI
                            MacTestForm.pointset_Form.UpdateSensor1Location(nEnPos.ToString());
                            iRecordLocation1_Step = 0;
                        }
                        break;
                    case 15:
                        // 其他步骤
                        break;
                }
                Thread.Sleep(10); // 添加延迟减少CPU占用
            }
        }

        private void RecordLocation2FlowThread(object obj)
        {
            while (RecordLocation2_Flowrec)
            {
                switch (iRecordLocation2_Step)
                {
                    case 0:
                        // 初始状态
                        break;

                    case 10:
                        if (DIO_Thread.Di[12] == 1)
                        {
                            UInt32 nEnPos = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 1);
                            // 通过单例实例更新UI
                            MacTestForm.pointset_Form.UpdateSensor2Location(nEnPos.ToString());
                            iRecordLocation2_Step = 0;
                        }
                        break;
                    case 15:
                        // 其他步骤
                        break;
                }
                Thread.Sleep(10); // 添加延迟减少CPU占用
            }
        }

        private void RecordLocation3FlowThread(object obj)
        {
            while (RecordLocation3_Flowrec)
            {
                switch (iRecordLocation3_Step)
                {
                    case 0:
                        // 初始状态
                        break;

                    case 10:
                        if (DIO_Thread.Di[11] == 1)
                        {
                            UInt32 Sensor1EnPos = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0);

                            MacTestForm.pointset_Form.UpdateSensor1Axis0LocationTb(Sensor1EnPos.ToString());
                            iRecordLocation3_Step = 15;
                        }
                        break;
                    case 15:
                        if (DIO_Thread.Di[12] == 1)
                        {
                            UInt32 Sensor2EnPos = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0);

                            MacTestForm.pointset_Form.UpdateSensor2Axis0LocationTb(Sensor2EnPos.ToString());
                            iRecordLocation3_Step = 0;
                        }
                        // 其他步骤
                        break;
                }
                Thread.Sleep(10); // 添加延迟减少CPU占用
            }
        }

        private void UpdateSensor1Axis0LocationTb(string str)
        {
            if (Sensor1Axis0LocationTb.InvokeRequired)
            {
                Sensor1Axis0LocationTb.BeginInvoke((MethodInvoker)delegate
                {
                    Sensor1Axis0LocationTb.Text = str;
                });
            }
            else
            {
                Sensor1Axis0LocationTb.Text = str;
            }
        }
        private void UpdateSensor2Axis0LocationTb(string str)
        {
            if (Sensor2Axis0LocationTb.InvokeRequired)
            {
                Sensor2Axis0LocationTb.BeginInvoke((MethodInvoker)delegate
                {
                    Sensor2Axis0LocationTb.Text = str;
                    CalculateSensorDistance(); // 统一计算函数
                });
            }
            else
            {
                Sensor2Axis0LocationTb.Text = str;
                CalculateSensorDistance(); // 统一计算函数
            }
        }

        private void CalculateSensorDistance()
        {
            try
            {
                // 调试信息：检查文本框内容
                string sensor1Text = Sensor1Axis0LocationTb.Text?.Trim() ?? "";
                string sensor2Text = Sensor2Axis0LocationTb.Text?.Trim() ?? "";

                Console.WriteLine($"Sensor1 Text: '{sensor1Text}'");
                Console.WriteLine($"Sensor2 Text: '{sensor2Text}'");

                // 检查是否为空
                if (string.IsNullOrEmpty(sensor1Text) || string.IsNullOrEmpty(sensor2Text))
                {
                    NewSensorDistanceTb.Text = "等待数据...";
                    return;
                }

                // 清理字符串（移除所有非数字字符，除了负号）
                sensor1Text = CleanNumericString(sensor1Text);
                sensor2Text = CleanNumericString(sensor2Text);

                Console.WriteLine($"Cleaned Sensor1: '{sensor1Text}'");
                Console.WriteLine($"Cleaned Sensor2: '{sensor2Text}'");

                // 尝试解析
                if (uint.TryParse(sensor1Text, out uint sensor1Pos) &&
                    uint.TryParse(sensor2Text, out uint sensor2Pos))
                {
                    if (sensor2Pos >= sensor1Pos)
                    {
                        uint distance = sensor2Pos - sensor1Pos;
                        NewSensorDistanceTb.Text = distance.ToString();
                        Console.WriteLine($"计算成功: {sensor2Pos} - {sensor1Pos} = {distance}");
                    }
                    else
                    {
                        NewSensorDistanceTb.Text = "传感器2位置小于传感器1";
                    }
                }
                else
                {
                    // 更详细的错误信息
                    bool canParse1 = uint.TryParse(sensor1Text, out _);
                    bool canParse2 = uint.TryParse(sensor2Text, out _);

                    NewSensorDistanceTb.Text = $"解析失败: Sensor1={canParse1}, Sensor2={canParse2}";
                    Console.WriteLine($"解析失败 - Sensor1可解析: {canParse1}, Sensor2可解析: {canParse2}");
                }
            }
            catch (Exception ex)
            {
                NewSensorDistanceTb.Text = $"错误: {ex.Message}";
                Console.WriteLine($"计算异常: {ex}");
            }
        }

        // 清理字符串，只保留数字
        private string CleanNumericString(string input)
        {
            if (string.IsNullOrEmpty(input)) return "";

            // 移除所有非数字字符
            return new string(input.Where(char.IsDigit).ToArray());
        }
        private void OnFormClosing(object sender, EventArgs e)
        {
            CameraContinuesThread01.iCameraContinues_Step = 2;
            CameraContinuesThread02.iCameraContinues_Step = 2;
            CameraContinuesThread03.iCameraContinues_Step = 2;
            // 停止传感器1线程
            RecordLocation1_Flowrec = false;
            if (RecordLocation1Flow_Thread != null && RecordLocation1Flow_Thread.IsAlive)
            {
                RecordLocation1Flow_Thread.Join(500);
            }

            // 停止传感器2线程
            RecordLocation2_Flowrec = false;
            if (RecordLocation2Flow_Thread != null && RecordLocation2Flow_Thread.IsAlive)
            {
                RecordLocation2Flow_Thread.Join(500);
            }

            RecordLocation3_Flowrec = false;
            if (RecordLocation3Flow_Thread != null && RecordLocation3Flow_Thread.IsAlive)
            {
                RecordLocation3Flow_Thread.Join(500);
            }
            MacTestForm.macTestForm.isPointSet = false;
            MacTestForm.pointset_Form = null;
            AddPointThread01.iAddPoint_Step = 10;
            AddPointThread02.iAddPoint_Step = 10;

        }       
        private void GetWork1Btn_Click(object sender, EventArgs e)
        {
            if (Sensor1Location.Text == string.Empty)
            {
                MessageBox.Show("请先获取传感器1位置");
                return;
            }
            Point1ValueAddBtn.Enabled = true;
            Point1ValueSubBtn.Enabled = true;
            UInt32 nEnPos = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 2);
            Work1Location.Text = nEnPos.ToString();
            Point1Tb.Text = (int.Parse(Work1Location.Text) - int.Parse(Sensor1Location.Text)).ToString();
        }

        private void GetWork2Btn_Click(object sender, EventArgs e)
        {
            if (Sensor1Location.Text == string.Empty)
            {
                MessageBox.Show("请先获取传感器1位置");
                return;
            }
            Point2ValueAddBtn.Enabled = true;
            Point2ValueSubBtn.Enabled = true;
            UInt32 nEnPos = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 1);
            Work2Location.Text = nEnPos.ToString();
            Point2Tb.Text = (int.Parse(Work2Location.Text) - int.Parse(Sensor1Location.Text)).ToString();
        }

        private void GetWork3Btn_Click(object sender, EventArgs e)
        {
            if(Sensor2Location.Text == string.Empty)
            {
                MessageBox.Show("请先获取传感器2位置");
                return;
            }
            Point3ValueAddBtn.Enabled = true;
            Point3ValueSubBtn.Enabled = true;
            UInt32 nEnPos = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0);
            Work3Location.Text = nEnPos.ToString();
            Point3Tb.Text = (int.Parse(Work3Location.Text) - int.Parse(Sensor2Location.Text)).ToString();
        }



        private void Point1ValueAddBtn_Click(object sender, EventArgs e)
        {
            textBox3.Text = (int.Parse(textBox3.Text) + 200).ToString();
            string filePath1 = MacTestForm.SettingsFilePath;
            JsonData jsonData1;
            string jsonContent1 = File.ReadAllText(filePath1);
            jsonData1 = JsonMapper.ToObject(jsonContent1);
            
            jsonData1["TaskGroup1"]["Interval"] = int.Parse(textBox3.Text);
        }

        private void Point1ValueSubBtn_Click(object sender, EventArgs e)
        {
            textBox3.Text = (int.Parse(textBox3.Text) - 200).ToString();
            string filePath1 = MacTestForm.SettingsFilePath;
            JsonData jsonData1;
            string jsonContent1 = File.ReadAllText(filePath1);
            jsonData1 = JsonMapper.ToObject(jsonContent1);

            jsonData1["TaskGroup1"]["Interval"] = int.Parse(textBox3.Text);
        }

        private void Point2ValueAddBtn_Click(object sender, EventArgs e)
        {
            textBox2.Text = (int.Parse(textBox2.Text) + 200).ToString();
            string filePath1 = MacTestForm.SettingsFilePath;
            JsonData jsonData1;
            string jsonContent1 = File.ReadAllText(filePath1);
            jsonData1 = JsonMapper.ToObject(jsonContent1);

            jsonData1["TaskGroup2"]["Interval"] = int.Parse(textBox2.Text);
        }

        private void Point2ValueSubBtn_Click(object sender, EventArgs e)
        {
            textBox2.Text = (int.Parse(textBox2.Text) - 200).ToString();
            string filePath1 = MacTestForm.SettingsFilePath;
            JsonData jsonData1;
            string jsonContent1 = File.ReadAllText(filePath1);
            jsonData1 = JsonMapper.ToObject(jsonContent1);

            jsonData1["TaskGroup2"]["Interval"] = int.Parse(textBox2.Text);
        }

        private void Point3ValueAddBtn_Click(object sender, EventArgs e)
        {
            textBox1.Text = (int.Parse(textBox1.Text) + 200).ToString();
            string filePath1 = MacTestForm.SettingsFilePath;
            JsonData jsonData1;
            string jsonContent1 = File.ReadAllText(filePath1);
            jsonData1 = JsonMapper.ToObject(jsonContent1);

            jsonData1["TaskGroup3"]["Interval"] = int.Parse(textBox1.Text);
        }

        private void Point3ValueSubBtn_Click(object sender, EventArgs e)
        {
            textBox1.Text = (int.Parse(textBox1.Text) - 200).ToString();
            string filePath1 = MacTestForm.SettingsFilePath;
            JsonData jsonData1;
            string jsonContent1 = File.ReadAllText(filePath1);
            jsonData1 = JsonMapper.ToObject(jsonContent1);

            jsonData1["TaskGroup3"]["Interval"] = int.Parse(textBox1.Text);
        }



        

        public bool isJOG;
        private void JOGModeButton_Click(object sender, EventArgs e)
        {
            if (!isJOG)
            {
                DIO_Thread.Do[14] = 1;
                Do14Button.Text = "真空：关";
            }
            else
            {
                DIO_Thread.Do[14] = 0;
                Do14Button.Text = "真空：开";
            }
            isJOG = !isJOG;
        }

        private void JOGSpeedAdd_Click(object sender, EventArgs e)
        {
            JOGSpeedTb.Text = (int.Parse(JOGSpeedTb.Text) + 100).ToString();
        }

        private void JOGSpeedSub_Click(object sender, EventArgs e)
        {
            JOGSpeedTb.Text = (int.Parse(JOGSpeedTb.Text) - 100).ToString();
        }


        public bool isStart = false;
        private DateTime lastQueueUpdateTime;





private void SaveValueToFileBtn_Click(object sender, EventArgs e)
    {
        try
        {
            // 弹出确认对话框
            DialogResult result = MessageBox.Show(
                "确定要更新参数到配置文件吗？\n\n" +
                $"TaskGroup1.json:\n" +
                $"  - TaskGroup1.Interval: {Point1Tb.Text}\n" +
                $"  - TaskGroup2.Interval: {Point2Tb.Text}\n\n" +
                $"TaskGroup2.json:\n" +
                $"  - TaskGroup1.Interval: {Point3Tb.Text}",
                "确认更新",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button2);

            // 如果用户选择"否"，则取消操作
            if (result != DialogResult.Yes)
            {
                return;
            }

            // 更新TaskGroup1.json文件
            UpdateTaskGroup1Json();

            // 更新TaskGroup2.json文件
            UpdateTaskGroup2Json();

            MessageBox.Show("参数保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void UpdateTaskGroup1Json()
    {
        string filePath = MacTestForm.SettingsFilePath;
        JsonData jsonData;

        // 读取现有的JSON文件，如果不存在则创建新的
        if (File.Exists(filePath))
        {
            string jsonContent = File.ReadAllText(filePath);
            jsonData = JsonMapper.ToObject(jsonContent);
        }
        else
        {
            jsonData = new JsonData();
            jsonData.SetJsonType(JsonType.Object);
        }

        // 确保TaskGroup1对象存在
        if (!jsonData.Keys.Contains("TaskGroup1"))
        {
            jsonData["TaskGroup1"] = new JsonData();
            jsonData["TaskGroup1"].SetJsonType(JsonType.Object);
        }

        // 确保TaskGroup2对象存在
        if (!jsonData.Keys.Contains("TaskGroup2"))
        {
            jsonData["TaskGroup2"] = new JsonData();
            jsonData["TaskGroup2"].SetJsonType(JsonType.Object);
        }

        // 更新Interval值
        jsonData["TaskGroup1"]["Interval"] = int.Parse(Point1Tb.Text);
        jsonData["TaskGroup2"]["Interval"] = int.Parse(Point2Tb.Text);

        // 设置默认的DoPin和ActionType（如果不存在）
        if (!jsonData["TaskGroup1"].Keys.Contains("DoPin"))
            jsonData["TaskGroup1"]["DoPin"] = 1;

        if (!jsonData["TaskGroup1"].Keys.Contains("ActionType"))
            jsonData["TaskGroup1"]["ActionType"] = 8;

        if (!jsonData["TaskGroup2"].Keys.Contains("DoPin"))
            jsonData["TaskGroup2"]["DoPin"] = 2;

        if (!jsonData["TaskGroup2"].Keys.Contains("ActionType"))
            jsonData["TaskGroup2"]["ActionType"] = 8;

        // 保存文件
        string updatedJson = jsonData.ToJson();
        File.WriteAllText(filePath, updatedJson);
    }

    private void UpdateTaskGroup2Json()
    {
        string filePath = MacTestForm.SettingsFilePath;
        JsonData jsonData;

        // 读取现有的JSON文件，如果不存在则创建新的
        if (File.Exists(filePath))
        {
            string jsonContent = File.ReadAllText(filePath);
            jsonData = JsonMapper.ToObject(jsonContent);
        }
        else
        {
            jsonData = new JsonData();
            jsonData.SetJsonType(JsonType.Object);
        }

        // 确保TaskGroup1对象存在
        if (!jsonData.Keys.Contains("TaskGroup3"))
        {
            jsonData["TaskGroup3"] = new JsonData();
            jsonData["TaskGroup3"].SetJsonType(JsonType.Object);
        }

        // 更新Interval值
        jsonData["TaskGroup3"]["Interval"] = int.Parse(Point3Tb.Text);

        // 设置默认的DoPin和ActionType（如果不存在）
        if (!jsonData["TaskGroup3"].Keys.Contains("DoPin"))
            jsonData["TaskGroup3"]["DoPin"] = 3;

        if (!jsonData["TaskGroup3"].Keys.Contains("ActionType"))
            jsonData["TaskGroup3"]["ActionType"] = 8;

        // 保存文件
        string updatedJson = jsonData.ToJson();
        File.WriteAllText(filePath, updatedJson);
    }

    private void JOGButton_MouseDown(object sender, MouseEventArgs e)
        {
            Param_Form.ContinuousMotion(0, "1000", JOGSpeedTb.Text, "0", "0", "1000", "0", false);
            Param_Form.ContinuousMotion(1, "1000", JOGSpeedTb.Text, "0", "0", "1000", "0", false);
            Param_Form.ContinuousMotion(2, "1000", JOGSpeedTb.Text, "0", "0", "1000", "0", true);
        }

        private void JOGButton_MouseUp(object sender, MouseEventArgs e)
        {
            Param_Form.stopAxis(0, "0");
            Param_Form.stopAxis(1, "0");
            Param_Form.stopAxis(2, "0");

        }

        private void BackJOGButton_MouseDown(object sender, MouseEventArgs e)
        {
            Param_Form.ContinuousMotion(0, "1000", JOGSpeedTb.Text, "0", "0", "1000", "0", true);
            Param_Form.ContinuousMotion(1, "1000", JOGSpeedTb.Text, "0", "0", "1000", "0", true);
            Param_Form.ContinuousMotion(2, "1000", JOGSpeedTb.Text, "0", "0", "1000", "0", false);
        }

        private void BackJOGButton_MouseUp(object sender, MouseEventArgs e)
        {
            Param_Form.stopAxis(0, "0");
            Param_Form.stopAxis(1, "0");
            Param_Form.stopAxis(2, "0");
        }


        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            CameraContinuesThread01.iCameraContinues_Step = 2;
            CameraContinuesThread02.iCameraContinues_Step = 2;
            CameraContinuesThread03.iCameraContinues_Step = 2;
            switch (tabControl1.SelectedIndex)
            {
                case 0:
                    CameraContinuesThread01.iCameraContinues_Step = 0;
                    break;
                case 1:
                    CameraContinuesThread02.iCameraContinues_Step = 0;
                    break;
                case 2:
                    CameraContinuesThread03.iCameraContinues_Step = 0;
                    break;

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(Point1Tb.Text))
                {
                    MessageBox.Show("请先获取相机1的触发位置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 弹出确认对话框
                DialogResult result = MessageBox.Show(
                    "确定要更新相机1的参数到配置文件吗？\n\n" +
                    $"  - TaskGroup1.Interval: {Point1Tb.Text}",
                    "确认更新",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button2);

                if (result != DialogResult.Yes)
                {
                    return;
                }

                // 只更新相机1的配置
                UpdateCamera1Config();

                MessageBox.Show("相机1参数保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(Point2Tb.Text))
                {
                    MessageBox.Show("请先获取相机2的触发位置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 弹出确认对话框
                DialogResult result = MessageBox.Show(
                    "确定要更新相机2的参数到配置文件吗？\n\n" +
                    $"  - TaskGroup2.Interval: {Point2Tb.Text}",
                    "确认更新",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button2);

                if (result != DialogResult.Yes)
                {
                    return;
                }

                // 只更新相机2的配置
                UpdateCamera2Config();

                MessageBox.Show("相机2参数保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(Point3Tb.Text))
                {
                    MessageBox.Show("请先获取相机3的触发位置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 弹出确认对话框
                DialogResult result = MessageBox.Show(
                    "确定要更新相机3的参数到配置文件吗？\n\n" +
                    $"  - TaskGroup1.Interval: {Point3Tb.Text}",
                    "确认更新",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button2);

                if (result != DialogResult.Yes)
                {
                    return;
                }

                // 只更新相机3的配置
                UpdateCamera3Config();

                MessageBox.Show("相机3参数保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void UpdateCamera1Config()
        {
            try
            {
                JsonData settings = new JsonData();

                // 读取现有配置
                if (File.Exists(MacTestForm.SettingsFilePath))
                {
                    string jsonContent = File.ReadAllText(MacTestForm.SettingsFilePath);
                    settings = JsonMapper.ToObject(jsonContent);
                }

                // 只更新TaskGroup1配置
                if (!settings.Keys.Contains(MacTestForm.ConfigKeys.TaskGroup1))
                {
                    settings[MacTestForm.ConfigKeys.TaskGroup1] = new JsonData();
                    settings[MacTestForm.ConfigKeys.TaskGroup1].SetJsonType(JsonType.Object);
                }

                settings[MacTestForm.ConfigKeys.TaskGroup1]["Interval"] = int.Parse(Point1Tb.Text);

                // 确保必要的字段存在
                if (!settings[MacTestForm.ConfigKeys.TaskGroup1].Keys.Contains("DoPin"))
                    settings[MacTestForm.ConfigKeys.TaskGroup1]["DoPin"] = 1;

                if (!settings[MacTestForm.ConfigKeys.TaskGroup1].Keys.Contains("ActionType"))
                    settings[MacTestForm.ConfigKeys.TaskGroup1]["ActionType"] = 8;

                File.WriteAllText(MacTestForm.SettingsFilePath, settings.ToJson());
                MessageBox.Show("相机1参数保存成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}");
            }
        }

        // 类似地修改其他相机配置方法
        private void UpdateCamera2Config()
        {
            try
            {
                JsonData settings = new JsonData();

                if (File.Exists(MacTestForm.SettingsFilePath))
                {
                    string jsonContent = File.ReadAllText(MacTestForm.SettingsFilePath);
                    settings = JsonMapper.ToObject(jsonContent);
                }

                // 只更新TaskGroup2配置
                if (!settings.Keys.Contains(MacTestForm.ConfigKeys.TaskGroup2))
                {
                    settings[MacTestForm.ConfigKeys.TaskGroup2] = new JsonData();
                    settings[MacTestForm.ConfigKeys.TaskGroup2].SetJsonType(JsonType.Object);
                }

                settings[MacTestForm.ConfigKeys.TaskGroup2]["Interval"] = int.Parse(Point2Tb.Text);

                if (!settings[MacTestForm.ConfigKeys.TaskGroup2].Keys.Contains("DoPin"))
                    settings[MacTestForm.ConfigKeys.TaskGroup2]["DoPin"] = 2;

                if (!settings[MacTestForm.ConfigKeys.TaskGroup2].Keys.Contains("ActionType"))
                    settings[MacTestForm.ConfigKeys.TaskGroup2]["ActionType"] = 8;

                File.WriteAllText(MacTestForm.SettingsFilePath, settings.ToJson());
                MessageBox.Show("相机2参数保存成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}");
            }
        }

        private void UpdateCamera3Config()
        {
            try
            {
                JsonData settings = new JsonData();

                if (File.Exists(MacTestForm.SettingsFilePath))
                {
                    string jsonContent = File.ReadAllText(MacTestForm.SettingsFilePath);
                    settings = JsonMapper.ToObject(jsonContent);
                }

                // 只更新TaskGroup3配置
                if (!settings.Keys.Contains(MacTestForm.ConfigKeys.TaskGroup3))
                {
                    settings[MacTestForm.ConfigKeys.TaskGroup3] = new JsonData();
                    settings[MacTestForm.ConfigKeys.TaskGroup3].SetJsonType(JsonType.Object);
                }

                settings[MacTestForm.ConfigKeys.TaskGroup3]["Interval"] = int.Parse(Point3Tb.Text);

                if (!settings[MacTestForm.ConfigKeys.TaskGroup3].Keys.Contains("DoPin"))
                    settings[MacTestForm.ConfigKeys.TaskGroup3]["DoPin"] = 3;

                if (!settings[MacTestForm.ConfigKeys.TaskGroup3].Keys.Contains("ActionType"))
                    settings[MacTestForm.ConfigKeys.TaskGroup3]["ActionType"] = 8;

                File.WriteAllText(MacTestForm.SettingsFilePath, settings.ToJson());
                MessageBox.Show("相机3参数保存成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}");
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {
            OldSensorDistanceTb.Text = (int.Parse(OldSensorDistanceTb.Text)+200).ToString();
            MaterialTracker.SENSOR1_TO_SENSOR2_DISTANCE = uint.Parse(OldSensorDistanceTb.Text);
            MacTestForm.macTestForm.SaveMergedConfig();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            OldSensorDistanceTb.Text = (int.Parse(OldSensorDistanceTb.Text) - 200).ToString();
            MaterialTracker.SENSOR1_TO_SENSOR2_DISTANCE = uint.Parse(OldSensorDistanceTb.Text);
            MacTestForm.macTestForm.SaveMergedConfig();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Sensor1Axis0LocationTb.Text))
            {
                MessageBox.Show("请先获取两个传感器的位置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            MaterialTracker.SENSOR1_TO_SENSOR2_DISTANCE = uint.Parse(NewSensorDistanceTb.Text);
            MacTestForm.macTestForm.SaveMergedConfig();
        }
    }
}